﻿using Android;
using Android.App;
using Android.Content.PM;
using Android.OS;
using Android.Runtime;
using Android.Widget;
using AndroidX.AppCompat.App;
using AndroidX.Core.App;
using AndroidX.Core.Content;
using Com.Netease.Nis.Quicklogin;
using Plugin.AudioRecorder;
using System.Threading.Tasks;

namespace AndioDemo.Droid
{
    [Activity(Label = "@string/app_name", Theme = "@style/AppTheme", MainLauncher = true)]
    public class MainActivity : AppCompatActivity
    {
        QuickLoginEx _quickLogin;
        string? _mobile;
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            Xamarin.Essentials.Platform.Init(this, savedInstanceState);
            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.activity_main);
            _recorder = new AudioRecorderService
            {
                StopRecordingOnSilence = false, //will stop recording after 2 seconds (default)
                StopRecordingAfterTimeout = false,  //stop recording after a max timeout (defined below)
                //TotalAudioTimeout = TimeSpan.FromSeconds(15) //audio will stop recording after 15 seconds
            };
            _quickLogin = QuickLoginEx.Instance;
            _quickLogin.Init(this, "01e659b45a3040f297c0824267ea39d7");
            _quickLogin.PrefetchMobileNumber(new QuickLoginPreMobileListener
            {
                Success = (mobile) => {
                    //取得手机号
                    _mobile = mobile;
                },
                Error = (msg) =>
                {
                    //失败
                    var xx = msg;
                }
            });


            var start = FindViewById<Button>(Resource.Id.start);
            var end = FindViewById<Button>(Resource.Id.end);
            var login = FindViewById<Button>(Resource.Id.login);

            login.Touch += Login_Touch;
            start.Touch += Start_Touch;
            end.Touch += End_Touch;

        }

        private void Login_Touch(object sender, Android.Views.View.TouchEventArgs e)
        {
            if (ContextCompat.CheckSelfPermission(this, Manifest.Permission.ReadPhoneState) != Permission.Granted)
            {
                ActivityCompat.RequestPermissions(this, new string[] { Manifest.Permission.ReadPhoneState }, 1);
                return;
            }
            if (!string.IsNullOrEmpty(_mobile))
            {
                var config = new Com.Netease.Nis.Quicklogin.Helper.UnifyUiConfig.Builder().Build(this);
                _quickLogin.SetUnifyUiConfig(config);
                //拉取授权页面
                _quickLogin.OnePass(new QuickLoginTokenListener
                {
                    Success = (token) =>
                    {
                        //登录成功
                        //TODO 与服务端交互登录成功
                        _quickLogin.QuitActivity();

                    },
                    Error = (msg) => {
                        var xx = msg;
                    }
                });
            }
        }

        AudioRecorderService _recorder;
        private void End_Touch(object sender, Android.Views.View.TouchEventArgs e)
        {
           _recorder.StopRecording();
        }

        private void Start_Touch(object sender, Android.Views.View.TouchEventArgs e)
        {
            //录音权限检查
            if (ContextCompat.CheckSelfPermission(this, Manifest.Permission.RecordAudio) != Permission.Granted)
            {
                ActivityCompat.RequestPermissions(this, new string[] { Manifest.Permission.RecordAudio }, 1);
                return;
            }
            _recorder.StartRecording();
            ProcessAudio();
        }

        private Task ProcessAudio()
        {
            return Task.Run(() => {
                while (_recorder.IsRecording)
                {
                    Task.Delay(500);
                    var stream = _recorder.GetAudioFileStream();
                    if (stream != null)
                    {
                        using (stream)
                        {
                            //注意：由于 WAV 标头是在录制后写入的，因此一旦知道音频长度，提供的数据将仅包含 PCM 音频数据，而不包含 WAV 标头。
                            //如果您的用例需要 WAV 标头，您可以调用 ，这会将 WAV 标头写入长度未知的流。
                            var wavStream = StreamAudioFunctions.WriteWaveHeader(stream);
                            //TODO 发送服务端
                        }
                    }
                }
            });
        }

        public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
        {
            Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);

            base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }
}